package com.xzj.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.xzj.common.aspect.WebAspect;
import com.xzj.common.core.domain.vo.R;
import com.xzj.common.core.constants.LogConstants;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO 描述
 *
 * @author xiazunjun
 * @date 2023/7/3 11:37
 */
@RestControllerAdvice
@Slf4j
@Order(2)
public class GlobResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private final List<String> blockList;

    {
        blockList = new ArrayList<>();
        blockList.add("swagger-resources");
        blockList.add("api-docs");
        blockList.add("favicon_1.ico");
    }

/*    @Resource
    private ObjectMapper objectMapper;*/

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    /**
     * 处理返回结果
     */
    @Override
    public Object beforeBodyWrite(Object result, MethodParameter methodParameter, MediaType mediaType,
        Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
        ServerHttpResponse serverHttpResponse) {
        String uri = serverHttpRequest.getURI().toString();
        log.info("{}", uri);
        for(String block : blockList){
            if(uri.contains(block)){
                return result;
            }
        }
        R ajaxResult;
        // 返回结果不为空，且返回类型已经封装
        if (ObjectUtil.isNotEmpty(result) && result instanceof R) {
            ajaxResult = (R)result;
        } else {
            ajaxResult = R.success().putResult(result);
            WebAspect.countExecuteTime(ajaxResult);
        }
        ajaxResult.putTraceId(MDC.get(LogConstants.TRACE_ID));
        return ajaxResult;
    }
}
